<script setup lang="ts">
import * as echarts from "echarts";
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from "vue";

const props = defineProps({
  options: {
    type: Object,
    default: () => {}
  }
});
const emit = defineEmits([
  "wheel",
  "contextmenu",
  "dblClick",
  "georoam",
  "uclick",
  "dataZoom",
  "mouseover",
  "resize"
]);
const chartRef = ref(null);

watch(
  () => props,
  async () => {
    await nextTick(); // 确保DOM更新完成后再执行
    myChart.setOption(props.options, true);
  },
  {
    deep: true
  }
);
let myChart = null;
const reseize = () => {
  setTimeout(() => {
    myChart && myChart.resize();
    emit("resize");
  }, 500);
};
const wheel = e => {
  let delta = e.deltaY > 0 ? "向下" : "向上";
  // 输出滚动方向和距离
  // console.log('滚动方向:', delta, '，滚动距离:', e.deltaY);
  emit("wheel", delta);
};

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function () {
      func.apply(context, args);
    }, wait);
  };
}

onMounted(() => {
  window.addEventListener("resize", reseize);
  window.addEventListener("wheel", wheel);
  myChart = echarts.init(chartRef.value);
  myChart.setOption(props.options, true);
  myChart.on("mouseover", e => {
    emit("mouseover", e);
  });
  myChart.on("click", e => {
    emit("uclick", e);
  });
  myChart.on("contextmenu", e => {
    emit("contextmenu", e);
  });
  myChart.on("dblclick", e => {
    emit("dblClick", e.region);
  });
  let myFunc = debounce(function (e) {
    emit("dataZoom", e);
  }, 300);
  myChart.on("dataZoom", e => {
    myFunc(e);
  });
  chartRef.value.oncontextmenu = function (e) {
    return false;
  };
  setTimeout(() => {
    myChart.resize();
  }, 200);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", reseize);
  window.removeEventListener("wheel", wheel);
});
</script>

<template>
  <div ref="chartRef" class="w-full not-right-click" />
</template>
